package com.ym.pms.security.provider;

import com.ym.pms.model.SysAuth;
import com.ym.pms.security.entity.SysUserDetails;
import com.ym.pms.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 11:41 2020/12/22
 * @Modified:
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 判断是否拥有权限
     *
     * @param authentication 用户身份
     * @param o              目标路径
     * @param o1             路径权限
     * @return 是否拥有权限
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        HashSet<String> permissions = new HashSet<>();

        List<SysAuth> authList = sysUserService.findAuthByUserId(sysUserDetails.getUId());
        authList.forEach(auth -> {
            permissions.add(auth.getPermission());
        });
        if (permissions.contains(o1.toString())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
